package com.liujun.demo.controller;

import com.liujun.demo.common.Constants;
import com.liujun.demo.util.NewBeeMallUtils;
import com.meituan.android.walle.ChannelWriter;
import com.meituan.android.walle.SignatureNotFoundException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class MutiChannelController {

    @GetMapping("/makeChannelApk")
    public String putChannel(HttpServletRequest httpServletRequest, String base, String channel){
        try {
            List<File> files = new ArrayList<>();
            files.add(new File(Constants.FILE_UPLOAD_DIC, base));
            File outputFile = makeChannelApk(files, null, channel);
            return NewBeeMallUtils.getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/apk/" + outputFile.getName();
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private File makeChannelApk(List<File> files, Map<String, String> extraInfo, String channel){
        final File inputFile = files.get(0);
        File outputFile = null;
        if (files.size() == 2) {
            outputFile = files.get(1);
        } else {
            final String name = FilenameUtils.getBaseName(inputFile.getName());
            final String extension = FilenameUtils.getExtension(inputFile.getName());
            final String newName = name + "_" + channel + "." + extension;
            outputFile = new File(inputFile.getParent(), newName);
        }
        if (inputFile.equals(outputFile)) {
            try {
                ChannelWriter.put(outputFile, channel, extraInfo);
            } catch (IOException | SignatureNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            try {
                FileUtils.copyFile(inputFile, outputFile);
                ChannelWriter.put(outputFile, channel, extraInfo);
            } catch (IOException | SignatureNotFoundException e) {
                e.printStackTrace();
            }
        }
        return outputFile;
    }

}
